package com.hand.wfive.loginAndVip.ui

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.text.TextPaint
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.hand.wfive.R
import com.hand.wfive.activity.PrivacyActivity
import com.hand.wfive.ad.AdConfig
import com.hand.wfive.adapter.VipContentAdapter
import com.hand.wfive.adapter.VipPriceConfigAdapter
import com.hand.wfive.dialog.BuyExitCouponTipsDialog
import com.hand.wfive.dialog.BuyExitTipsDialog
import com.hand.wfive.dialog.BuyProtocolTipDialog
import com.hand.wfive.loginAndVip.UserManager
import com.hand.wfive.loginAndVip.model.CouponModel
import com.hand.wfive.loginAndVip.model.VipGoodsModel
import com.hand.wfive.util.NoShakeBtnUtil
import com.hand.wfive.util.SpanUtils
import com.hand.wfive.view.countdowntime.CountDownTimerView

import kotlinx.android.synthetic.main.activity_vip_center.*
import org.jetbrains.anko.startActivity

/**
 * 我的 -> 会员中心(全屏购买页)
 */
class VipCenterActivity : BaseVipActivity() {

    companion object {
        @JvmStatic
        fun show(context: Context) {
            if (UserManager.getInstance().isLogin) {
                context.startActivity<VipCenterActivity>()
            } else {
                LoginIndexActivity.show(context, true)
            }
        }

        @JvmStatic
        fun getIntent(context: Context): Intent {
            return Intent(context, VipCenterActivity::class.java)
        }
    }

    private lateinit var mVipConfigAdapter: VipPriceConfigAdapter
    private lateinit var mVipContentAdapter: VipContentAdapter
    private var isHasClickPay = false //是否有点击过支付

    override fun getContentViewId() = R.layout.activity_vip_center

    override fun getView(): View {
        return topBar
    }

    override fun initViewData() {
        super.initViewData()
        topBar.setTitle("会员中心").setTextColor(Color.BLACK)
        topBar.addLeftBackImageButton().setOnClickListener { doOnBackPressed() }
        topBar.updateBottomSeparatorColor(Color.TRANSPARENT)

        initAdapter()
        initVipContentAdapter()
        rbWechat.isChecked = true
        setProtocolStyle()
    }

    private fun initAdapter() {
        mVipConfigAdapter = VipPriceConfigAdapter()
        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
        rvVipConfig.layoutManager = linearLayoutManager
        rvVipConfig.adapter = mVipConfigAdapter
        mVipConfigAdapter.setOnItemClickListener { _, _, position ->
            mVipConfigAdapter.updateCheckPosition(position)
            mCurVipModel = mVipConfigAdapter.getItem(position)
            tvTotalPrice.text = setPriceStyle(mCurVipModel?.productPrice ?: "")
            setOriginPriceStyle(mCurVipModel?.productOriginalPrice ?: "")
            updateCurrentCoupon()
        }
    }

    private fun initVipContentAdapter() {
        mVipContentAdapter = VipContentAdapter()
        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
        rvVipContent.layoutManager = linearLayoutManager
        rvVipContent.adapter = mVipContentAdapter
        mVipContentAdapter.setList(
            arrayListOf(
                R.mipmap.icon_vip_content1,
            )
        )
    }

    @SuppressLint("SetTextI18n")
    override fun onNetSuccess(redId: Int) {
        if (redId == REQ_ID_VIP_ACTIVITY) {
            if (mActivityConfigModel.getDownTimeMills() <= 0) {
                setActivityDataVisible()
                return
            }
            setActivityDataVisible(true)
            val activityDownTime = getRemainderTime(mActivityConfigModel.getDownTimeMills(), 1)
            val couponDownTime = mCurrentCouponModel?.getDownTimeMills() ?: 0L
            startActivityCountDownTime(activityDownTime, downTimeView)
            startCouponCountDownTime(couponDownTime, downTimeViewTip)
            Glide.with(this).load(mActivityConfigModel.saleBanner)
                .error(R.mipmap.bg_banner1)
                .placeholder(R.mipmap.bg_banner1)
                .into(ivVipBanner)
            Glide.with(this).load(mActivityConfigModel.backgroundUrl)
                .error(R.mipmap.bg_vip)
                .placeholder(R.mipmap.bg_vip)
                .into(ivTopBackground)
            Glide.with(mContext)
                .asBitmap()
                .placeholder(R.mipmap.bg_red_solid)
                .load(mActivityConfigModel.imageUrl)
                .into(object : SimpleTarget<Bitmap>() {
                    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                        val drawable: Drawable = BitmapDrawable(resources, resource)
                        viewCountDown.background = drawable
                    }
                })
            tvActivityTitle.text = mActivityConfigModel.activeName + "："
            setOriginPriceStyle((mCurVipModel?.productOriginalPrice ?: ""))
        } else if (redId == REQ_ID_VIP_PRICE) {
            mVipConfigAdapter.setList(mVipConfigList)
            mVipConfigList.forEachIndexed { index, vipGoodsModel ->
                if (vipGoodsModel.isSelect == 1) {
                    mVipConfigAdapter.updateCheckPosition(index)
                }
            }
            setOriginPriceStyle((mCurVipModel?.productOriginalPrice ?: ""))
//            setSelectPrice(mCurVipModel?.productPrice ?: "", mCurVipModel?.productOriginalPrice ?: "")
        }
    }

    override fun onNetSuccessNoData(redId: Int) {
        if (redId == REQ_ID_VIP_ACTIVITY) {
            setActivityDataVisible()
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onUpdateCurrentCoupon(coupon: CouponModel?) {
        if (coupon == null) {
            viewCoupon.isVisible = false
            tvCouponDesc.text = "${mCurVipModel?.accName}暂无优惠券"
            tvCouponDesc.tag = 1
            setCouponOverdue()
        } else if (coupon.couponStartTime <= 0) { //优惠券过期
            viewCoupon.isVisible = true
            if (AdConfig.isHuawei()) {
                tvCouponDesc.text = "${mCurVipModel?.accName}暂无优惠券"
                tvCouponDesc.tag = 1
            } else {
                tvCouponDesc.text = "点击领取优惠劵，最高享0元购"
                tvCouponDesc.tag = 0
            }
            setCouponOverdue()
        } else {
            viewCoupon.isVisible = true
            tvCouponDesc.text = "${coupon.getVipValueByValue()}优惠券立减${coupon.price}"
            tvCouponDesc.tag = 1
            val price = getSelectPrice()
            val currentPrice = getCurrentPrice(price ?: "")
            tvTotalPrice.text = setPriceStyle(currentPrice)
            viewTimeTip.isVisible = true
            val couponDownTime = mCurrentCouponModel?.getDownTimeMills() ?: 0L
            startCouponCountDownTime(couponDownTime, downTimeViewTip)
            if (mCurVipModel == null || TextUtils.isEmpty(coupon.retContent)) {
                tvCouponTimeTip.text = "距离优惠结束仅剩"
            } else {
                tvCouponTimeTip.text = coupon.retContent
            }
        }
        setOriginPriceStyle(mCurVipModel?.productOriginalPrice ?: "")
    }

    override fun getPageType() = PageTypeEnum.PAGE_TYPE_VIP.type

    /**
     * 优惠券过期
     */
    private fun setCouponOverdue() {
        val price = getSelectPrice()
        tvTotalPrice.text = setPriceStyle(price.toString())
        viewTimeTip.isVisible = false
        downTimeViewTip.cancelDownTimer()
    }

    @SuppressLint("SetTextI18n")
    private fun setOriginPriceStyle(originPrice: String) {
        if (mCurrentCouponModel == null || !isHasCoupon) {
            if (!TextUtils.isEmpty(originPrice)) {
                tvOriginPrice.text = "原价¥$originPrice"
                tvOriginPrice.setTextColor(ContextCompat.getColor(mContext, R.color.gray_95))
                tvOriginPrice.paintFlags = tvOriginPrice.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
                tvOriginPrice.isVisible = true
            } else {
                tvOriginPrice.isVisible = false
            }
        } else {
            tvOriginPrice.text = "优惠券：${mCurrentCouponModel?.retContent}"
            tvOriginPrice.setTextColor(ContextCompat.getColor(mContext, R.color.red_FF4A4B))
            tvOriginPrice.paintFlags = tvOriginPrice.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
            tvOriginPrice.isVisible = true
        }
    }

    /**
     * 开启活动倒计时
     */
    private fun startActivityCountDownTime(millisecond: Long, timeView: CountDownTimerView) {
        downTimeView.cancelDownTimer()
        timeView.setDownTime(millisecond)
        timeView.setDownTimerListener {
            deleteAllCoupon()
            refreshData()
            /*if (mActivityConfigModel.activeType == 1 || mActivityConfigModel.activeType == 3) {
                refreshData()
            } else {
                setActivityDataVisible()
            }*/
        }
        timeView.startDownTimer()
    }

    /**
     * 开启优惠券倒计时
     */
    private fun startCouponCountDownTime(totalDownTimeMillisecond: Long, timeView: CountDownTimerView) {
        if (totalDownTimeMillisecond <= 0 || !isHasCoupon || (mCurrentCouponModel?.couponStartTime ?: 0) <= 0) {
            return
        }
        downTimeViewTip.cancelDownTimer()
        val remainderDownTime = getRemainderTime(
            mCurrentCouponModel?.getDownTimeMills() ?: 0L,
            2,
            mCurrentCouponModel?.couponStartTime ?: 0L
        )
        timeView.setDownTime(remainderDownTime)
        timeView.setDownTimerListener {
            deleteCurrentCoupon()
        }
        timeView.startDownTimer()
    }

    private fun setActivityDataVisible(isVisible: Boolean = false) {
        viewCountDown.isVisible = isVisible
        ivVipBanner.isVisible = isVisible
        /*val isFestival = mActivityConfigModel.activeType == 3
        viewCoupon.isVisible = !isFestival*/
        if (!isVisible) {
            viewTimeTip.isVisible = isVisible
        }
    }

    @SuppressLint("SetTextI18n")
    fun vipBtnClick(view: View) {
        when (view) {
            openVip -> {
                doOpenVip(getSelectPrice())
            }

            ivVipBanner -> {
                if (mActivityConfigModel.activeType != 3) {
                    return
                }
                if (mVipConfigList.isEmpty() || mVipConfigList.size <= 0) {
                    showNormalTip(topBar, "会员数据加载失败")
                    return
                }
                doOpenVip(mVipConfigList[0].productPrice, mVipConfigList[0])
            }

            buyNow -> PrivacyActivity.showRule(this, PrivacyActivity.VIPRULE)
            viewCoupon -> {
                if (NoShakeBtnUtil.isFastDoubleClick()) {
                    return
                }
                if (tvCouponDesc.tag == 1) {
                    return
                }
                showSuccessTip(topBar, "优惠券已领取")
                updateCouponStatus()
            }
        }
    }

    private fun doOpenVip(price: String?, vipGoodsModel: VipGoodsModel? = mCurVipModel) {
        if (NoShakeBtnUtil.isFastDoubleClick()) {
            return
        }
        if (UserManager.getInstance().isVip) {
            showNormalTip(topBar, "您已经是会员了")
            return
        }
        if (!rbAlipay.isChecked && !rbWechat.isChecked) {
            showNormalTip(topBar, "请选择支付方式")
            return
        }
        if (price.isNullOrEmpty()) {
            showErrorToast("会员数据加载失败")
        } else {
            isHasClickPay = true
            if (buyNow.isSelected) {
                doPay(price, rbWechat.isChecked, vipGoodsModel)
            } else {
                BuyProtocolTipDialog.showDialog(mContext, object : BuyProtocolTipDialog.TipListener {
                    override fun doBuy() {
                        buyNow.isSelected = true
                        doPay(price, rbWechat.isChecked, vipGoodsModel)
                    }
                })
            }
        }
    }

    override fun doOnBackPressed() {
        if (!UserManager.getInstance().isVip) {
            if (mVipActivityModel.couponList != null && mVipActivityModel.couponList?.isNotEmpty() == true) {
                BuyExitCouponTipsDialog.showDialog(
                    mContext,
                    mVipActivityModel,
                    downTimeView.currentMills,
                    object : BuyExitCouponTipsDialog.VipTipListener {
                        override fun doClose() {
                            super@VipCenterActivity.doOnBackPressed()
                        }

                        override fun doBuy() {
                            showSuccessTip(topBar, "优惠券已领取")
                            updateCouponStatus()
                        }
                    })
            } else {
                BuyExitTipsDialog.showVipDialog(mContext, object : BuyExitTipsDialog.VipTipListener {
                    override fun doClose() {
                        super@VipCenterActivity.doOnBackPressed()
                    }
                })
            }
        } else {
            super@VipCenterActivity.doOnBackPressed()
        }
    }

    private fun setProtocolStyle() {
        val sp = SpanUtils()
        sp.append("我已阅读并同意")
            .setClickSpan(object : ClickableSpan() {
                override fun onClick(widget: View) {
                    buyNow.isSelected = !buyNow.isSelected
                }

                /**
                 * 重写父类updateDrawState方法  可以给TextView设置字体颜色,背景颜色等等...
                 */
                override fun updateDrawState(ds: TextPaint) {
                    ds.color = ContextCompat.getColor(mContext, R.color.gray_95)
                }
            })
            .append("《购买协议》").setForegroundColor(ContextCompat.getColor(mContext, R.color.orange_ECAB5E))
            .setClickSpan(object : ClickableSpan() {
                override fun onClick(widget: View) {
                    PrivacyActivity.showRule(mContext, PrivacyActivity.VIPRULE)
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.color = ContextCompat.getColor(mContext, R.color.orange_ECAB5E)
                    ds.isUnderlineText = false
                }
            })
        buyNow.text = sp.create()
        buyNow.movementMethod = LinkMovementMethod.getInstance()
        buyNow.highlightColor = Color.TRANSPARENT; // 设置点击无颜色
    }

    override fun onDestroy() {
        downTimeView?.cancelDownTimer()
        downTimeViewTip?.cancelDownTimer()
        super.onDestroy()
    }
}
